<?php
declare (strict_types = 1);

namespace app\common\service;

use app\admin\service\BaseService;
use app\admin\service\ConfigService;
use app\common\libs\upload\Aliyun;
use app\common\libs\upload\Local;
use app\common\model\AttachmentModel;

/**
 * 上传服务
 *
 * @Author tanruizheng
 * @DateTime 2021-07-19
 */
class UploadService extends BaseService
{

    /**
     * 上传类型
     *
     * @var array
     * @Author tanruizheng
     * @DateTime 2021-07-19
     */
    private $uploadDrivers = [
        'Local' => Local::class,//本地上传
        'Aliyun' => Aliyun::class,//OSS上传
    ];

    /**
     * 上传图片
     *
     * @Author tanruizheng
     * @DateTime 2021-07-19
     * @return object
     */
    public function uploadImage($userId = 0,$isAdmin = 1){
        $file = request()->file('file');
        $originalMime = $file->getOriginalMime();
        if(strpos($originalMime,'image/') === false){
            $this->setError('请上传图片格式!');
            return false;
        }
        $attachment = new AttachmentModel();
        $attachment->userid = $userId;
        $attachment->isadmin = $isAdmin;
        $attachment->module = AttachmentModel::MODULE_IMAGE;
        $res = $this->upload($attachment);
        if(!$res){
            return false;
        }
        $attachment->isimage = AttachmentModel::IS_IMAGE_YES;
        $attachment->filethumb = $attachment->getData('fileurl');//缩略图
        $attachment->save();
        return $attachment;
    }

    /**
     * 上传视频
     *
     * @Author tanruizheng
     * @DateTime 2021-07-19
     * @return object
     */
    public function uploadVideo($userId = 0,$isAdmin = 1){
        //视频格式
        $file = request()->file('file');
        $originalMime = $file->getOriginalMime();
        if(strpos($originalMime,'video/') === false){
            $this->setError('请上传视频格式!');
            return false;
        }
        $attachment = new AttachmentModel();
        $attachment->userid = $userId;
        $attachment->isadmin = $isAdmin;
        $attachment->module = AttachmentModel::MODULE_VIDEO;
        $res = $this->upload($attachment);
        if(!$res){
            return false;
        }
        $attachment->isimage = AttachmentModel::IS_IMAGE_NO;
        $attachment->save();
        return $attachment;
    }

    /**
     * 上传文件
     *
     * @Author tanruizheng
     * @DateTime 2021-07-19
     * @return object
     */
    public function uploadFile($userId = 0,$isAdmin = 1){
        $attachment = new AttachmentModel();
        $attachment->userid = $userId;
        $attachment->isadmin = $isAdmin;
        $attachment->module = AttachmentModel::MODULE_FILE;
        $res = $this->upload($attachment);
        if(!$res){
            return false;
        }
        $attachment->isimage = AttachmentModel::IS_IMAGE_NO;
        $attachment->save();
        return $attachment;
    }

    /**
     * 上传操作
     *
     * @Author tanruizheng
     * @DateTime 2021-07-19
     * @return void
     */
    public function upload(AttachmentModel $attachment){
        // 获取表单上传文件
        $file = request()->file('file');
        $attachment->filename = $file->getOriginalName();
        $attachment->filesize = $file->getSize();
        $attachment->fileext = $file->getOriginalExtension();
        $attachment->uploadtime = time();
        $attachment->uploadip = request()->ip();
        $attachment->authcode = $file->hash('md5');
        try {
            $config = ConfigService::getConfig()['data'];
            if($attachment->isadmin){
                $uploadmaxsize = $config['uploadmaxsize'] ?: 1024;
                $uploadallowext = $config['uploadallowext'] ?: '';
            }else{
                $uploadmaxsize = $config['qtuploadmaxsize'] ?: 1024;
                $uploadallowext = $config['qtuploadallowext'] ?: '';
            }
            $uploadallowext = str_replace('|',',',$uploadallowext);
            validate(['file'=>"filesize:{$uploadmaxsize}|fileExt:{$uploadallowext}"])
                ->message([
                    'file.filesize' => '文件大小不能超过'.round($uploadmaxsize/1024,2).'KB',
                    'file.fileExt' => '文件格式错误',
                ])
                ->check(request()->file());
        } catch (\think\exception\ValidateException $e) {
            $this->setError($e->getMessage());
            return false;
        }
        $attachmentDriver = ConfigService::getConfig('attachment_driver')['data'] ?: 'Local';
        $uploadDrivers = $this->uploadDrivers[$attachmentDriver];
        if(isset($this->uploadDrivers[$attachmentDriver])){
            try {
                $config = ConfigService::getConfig()['data'];
                $drivers = new $uploadDrivers($config);
                $drivers->upload($attachment);
            } catch (\Exception $e) {
                $this->setError($e->getMessage());
                return false;
            }
        }else{
            return false;
        }
        return true;
    }
    
}
